package com.kunchi.platform.controller;

import com.kunchi.platform.model.device.DataItem;
import com.kunchi.platform.model.device.Device;
import com.kunchi.platform.model.device.DeviceMode;
import com.kunchi.platform.service.CompanyService;
import com.kunchi.platform.service.DeviceService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * Created by denniszhou on 2017/6/24.
 */
@Controller
@RequestMapping(value = "/device")
public class DeviceController {

  @Autowired
  DeviceService deviceService;

  @Autowired
  CompanyService companyService;

  @RequestMapping(value = "/all", method = RequestMethod.GET)
  public List<Device> getDeviceList(
      @RequestParam(name = "device_id", required = false) List<Long> deviceIds,
      @RequestParam(name = "device_name", required = false) String deviceName,
      @RequestParam(name = "serial_number", required = false) String serialNumber)
      throws IOException {
    Stream<Device> stream = deviceService.getDeviceList().stream();
    if (!Objects.isNull(deviceIds)) {
      stream = stream.filter(s -> deviceIds.contains(s.getId()));
    }
    if (!StringUtils.isEmpty(deviceName)) {
      stream = stream.filter(s -> s.getName().equals(deviceName));
    }
    if (!StringUtils.isEmpty(serialNumber)) {
      stream = stream.filter(s -> s.getSerialNumber().equals(serialNumber));
    }
    return stream.collect(Collectors.toList());
  }

  @RequestMapping(method = RequestMethod.GET)
  public Device getDevice(@RequestParam(name = "device_id") String deviceId) throws IOException {
    return deviceService.getDevice(deviceId);
  }

  @RequestMapping(value = "/mode/all", method = RequestMethod.GET)
  public List<DeviceMode> getDeviceModeList() throws IOException {
    return deviceService.getDeviceModeList();
  }

  @RequestMapping(value = "/dataitem", method = RequestMethod.GET)
  public List<DataItem> getDataItemList(@RequestParam(name = "device_id") String deviceId)
      throws IOException {
    return deviceService.getDataItemList(deviceId);
  }


}
